import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';

import { Divider, InputNumber, message, Tooltip } from 'antd';
import { history } from 'umi'

import IconFont from '@/components/IconFont';
import LinkTo from '@/components/LinkTo';
import { useRequest } from '@/hooks';
import { DividerContainer } from '@/molecules';
import { removeEntryRemindMailTemplate } from '@/pages/TurnoverSetting/EntrySetting/services';
import { onSuccessByDeleteFn } from '@/pages/TurnoverSetting/EntrySetting/util';

import ButtonPopconfirmAndToolTip from '../../components/ButtonPopconfirmAndToolTip';
import EntryRemindMailPreview from '../../EntryRemindMailSetting/EntryRemindMailPreview';
import { editEntryMailDay } from '../../services';
import styles from '../index.less';
import SettingTable from './SettingTable';

// 入职流程配置
const SectionEntryRemindMailSetting = props => {
    const { data, days, loading, onChange, ...otherProps } = props;
    const [remindDate, setRemindDate] = useState(0);

    // 数据获取成功更改 提醒日期
    useEffect(() => {
        setRemindDate(days);
    }, [days]);

    const [remindDateTemp, setRemindDateTemp] = useState(0);
    const [remindDateEditSwitch, setRemindDateEditSwitch] = useState(false);
    // const handleDelete = () => {};
    const { run: deleteRun, loading: deleteLoading } = useRequest(id => removeEntryRemindMailTemplate(id), {
        manual: true,
        onSuccess: res => {
            onSuccessByDeleteFn(res, onChange);
        }
    });

    const handleEdit = record => {
        history.push({
            pathname: '/office/personnelManagement/onboardAndLeave/setting/entryRemindMail/edit',
            query: { id: record.id }
        });
    };

    const handleViewDetail = record => {
        history.push({
            pathname: '/office/personnelManagement/onboardAndLeave/setting/entryRemindMail/detail',
            query: { id: record.id },
            state: { tabRoute: true, tabRefresh: true }
        });
    };

    const handleAdd = useCallback(() => {
        history.push({
            pathname: '/office/personnelManagement/onboardAndLeave/setting/entryRemindMail/add'
            // state: { tabRoute: true, tabRefresh: true }
        });
    }, []);

    const previewRef = useRef();
    const handlePreview = useCallback(record => {
        previewRef.current.open(record.id);
    }, []);

    const handleChangeRemindDate = useCallback(async () => {
        if (remindDateTemp) {
            const { code, msg } = await editEntryMailDay({ days: remindDateTemp });
            if (code === 10000) {
                setRemindDate(remindDateTemp);
                setRemindDateEditSwitch(false);
                message.success('保存成功');
            } else {
                message.error(`保存失败: ${msg ?? ''}`);
            }
        } else {
            message.error('请输入提醒日期');
        }
    }, [remindDateTemp]);

    // 渲染提醒日期
    const renderDateEditor = useMemo(() => {
        if (loading) {
            return null;
        }
        if (!remindDateEditSwitch) {
            return (
                <div className={styles.remindDateInput}>
                    提醒日期: 入职前 {remindDate} 天
                    <Tooltip title="编辑">
                        <a onClick={() => setRemindDateEditSwitch(true)}>
                            <IconFont icon="iconlistfunction_edit_icon_default" />
                        </a>
                    </Tooltip>
                </div>
            );
        }
        return (
            <div className={styles.remindDateInput}>
                提醒日期: 入职前&emsp;
                <InputNumber
                    size="small"
                    min={1}
                    max={180}
                    onChange={setRemindDateTemp}
                    defaultValue={remindDate}
                    style={{ margin: '0 4px', width: 70 }}
                />
                天&emsp;
                <Tooltip title="保存">
                    <IconFont isButton icon="iconconfirm_o" onClick={handleChangeRemindDate} />
                </Tooltip>
                <Divider type="vertical" />
                <Tooltip title="取消">
                    <IconFont
                        isButton
                        icon="iconcancel_o"
                        onClick={() => {
                            setRemindDateTemp(remindDate);
                            setRemindDateEditSwitch(false);
                        }}
                    />
                </Tooltip>
            </div>
        );
    }, [handleChangeRemindDate, loading, remindDate, remindDateEditSwitch]);

    return (
        <div {...otherProps}>
            <div className={styles.sectionTitle}>入职提醒邮件模板</div>
            <div className={styles.sectionDesc}>
                <p>邮件通知新员工前来公司报到并办理入职，默认提醒日期上午08:00发送</p>
            </div>
            {renderDateEditor}
            <SettingTable
                dataSource={data}
                loading={loading || deleteLoading}
                columns={[
                    {
                        title: '模板名称',
                        dataIndex: 'settingName',
                        render: (text, record) => (
                            <LinkTo isDefault onClick={() => handleViewDetail(record)}>
                                {text}
                            </LinkTo>
                        )
                    },
                    {
                        title: '邮件标题',
                        dataIndex: 'contentTitle'
                    },
                    {
                        title: '适用行政机构',
                        dataIndex: 'administrativeScopeNames',
                        render: (text, record) => (record.isDefault === 1 ? '全集团' : text?.join('、'))
                    },
                    {
                        title: '操作',
                        key: 'operation',
                        width: 140,
                        render: (text, record) => (
                            <DividerContainer>
                                <Tooltip title="预览">
                                    <IconFont
                                        isButton
                                        style={{
                                            fontSize: '20px',
                                            verticalAlign: 'middle'
                                        }}
                                        icon="iconchakanxiangqing"
                                        onClick={() => handlePreview(record)}
                                    />
                                </Tooltip>
                                <Tooltip placement="top" title="编辑">
                                    <IconFont
                                        style={{ verticalAlign: 'middle' }}
                                        onClick={() => handleEdit(record)}
                                        icon="iconlistfunction_edit_icon_default"
                                        isButton
                                    />
                                </Tooltip>
                                <ButtonPopconfirmAndToolTip
                                    title="你确定要删除这行内容吗？"
                                    tooltipTitle={record.isDefault === 1 ? '默认配置，不可删除' : '删除'}
                                    onConfirm={() => deleteRun(record.id)}
                                    disabled={record.isDefault === 1}
                                >
                                    <IconFont icon="iconlistfunction_delete_icon_default" isButton />
                                </ButtonPopconfirmAndToolTip>
                            </DividerContainer>
                        )
                    }
                ]}
                onAdd={handleAdd}
            />
            <EntryRemindMailPreview ref={previewRef} />
        </div>
    );
};

export default SectionEntryRemindMailSetting;
